package com.hm.service.impl.wx;

import com.alibaba.fastjson2.JSONArray;
import com.hm.service.framework.base.BaseServiceImpl;
import com.hm.service.service.wx.SubmitCaseService;
import com.hm.service.service.wx.WeChatPublicService;
import com.hm.service.utils.SoleIdUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service
public class SubmitCaseServiceImpl extends BaseServiceImpl implements SubmitCaseService {

    private static final Logger logger = LoggerFactory.getLogger(SubmitCaseServiceImpl.class);

    //图片文件夹存放路径（win）
    private static final String FolderPicPath = "D:/opencv-test/wx/";

    private final WeChatPublicService weChatPublicService;

    @Qualifier("OkHttpClient")
    public OkHttpClient okHttpClient;

    public SubmitCaseServiceImpl(OkHttpClient okHttpClient, WeChatPublicService weChatPublicService) {
        this.weChatPublicService = weChatPublicService;
        this.okHttpClient = okHttpClient;
    }

    /**
     * 根据serverId获取素材
     */
    @Override
    public String submitCase(JSONArray serverIdList) {
        String accessToken = weChatPublicService.getStableAccessToken();
        if (accessToken == null || accessToken.isEmpty()) {
            return generateFail("accessToken为空");
        }
        if (serverIdList == null || serverIdList.isEmpty()) {
            return generateFail("serverIdList为空");
        }
        //1、取出所有serverId
        int size = serverIdList.size();
        for (int i = 0; i < size; i++) {
            String serverId = serverIdList.getString(i);
            getPic(accessToken, serverId); //获取图片
        }
        return generateSucceed("请求成功");
    }

    private void getPic(String accessToken, String serverId) {
        String reqUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + serverId;
        Request build = new Request.Builder().url(reqUrl).build();
        try (Response response = okHttpClient.newCall(build).execute()) {
            //从请求头获取文件名
            String headers = response.headers("Content-disposition").toString();
            logger.error("headers:{}", headers);
            String picName = SoleIdUtils.getUUID() + ".png";//默认图片名字
            //匹配双引号之间的内容
            Pattern pattern = Pattern.compile("\"([^\"]*)\"");
            Matcher matcher = pattern.matcher(headers);
            while (matcher.find()) {
                //双引号之前的内容为文件名
                String group = matcher.group(1);
                if (group != null && !group.isEmpty()) {
                    picName = matcher.group(1);
                }
            }
            //开始下载
            ResponseBody resBody = response.body();
            if (response.isSuccessful() && resBody != null) {
                String path = FolderPicPath + picName;
                InputStream inputStream = resBody.byteStream();
                try (FileOutputStream outStream = new FileOutputStream(path)) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, bytesRead);
                    }
                    logger.error("素材写入成功");
                }
            }
        } catch (Exception e) {
            logger.error("获取素材异常：Exception: {}", e.getMessage());
        }

    }
}
